package controllers

import (
	"fmt"
	"go/dao"
	"go/models"
	"go/pkg/app"
	"go/pkg/e"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func AddCourse(c *gin.Context) {
	m := make(map[string]string, 1024)
	c.ShouldBind(&m)
	fmt.Println(m)
	cno := m["cno"]
	cname := m["cname"]

	course := models.Course{
		Cno:   cno,
		Cname: cname,
		IsDel: false,
	}

	err := dao.AddCourse(course)

	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, course, "添加成功")
}

func DelCourse(c *gin.Context) {
	json := make(map[string]string, 1024)
	c.ShouldBind(&json)
	fmt.Println(json)

	cno := json["cno"]
	cname := json["cname"]

	course := models.Course{
		Cno:   cno,
		Cname: cname,
		IsDel: true,
	}

	db := dao.GetDB()
	err := db.Table("course").Where("cno = ?", cno).Update("is_del", true).Error
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, course, "删除成功")
}

func UpdateCourse(c *gin.Context) {
	m := make(map[string]string, 1024)
	c.ShouldBind(&m)
	fmt.Println(m)
	cno := m["cno"]
	cname := m["cname"]

	course := models.Course{
		Cno:   cno,
		Cname: cname,
	}

	err := dao.UpdateCourse(course)

	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, course, "更新成功")
}

func GetCourse(c *gin.Context) {
	page := -1
	if arg := c.Query("page"); arg != "" {
		page = com.StrTo(arg).MustInt()
	}
	limit := -1
	if arg := c.Query("limit"); arg != "" {
		limit = com.StrTo(arg).MustInt()
	}
	searchName := ""
	if arg := c.Query("searchName"); arg != "" {
		searchName = arg
	}
	courseParam := map[string]interface{}{
		"page":       page,
		"limit":      limit,
		"searchName": searchName,
	}
	info, total, err := dao.GetCourse(courseParam)
	//fmt.Println(info);
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "OK")
}
